package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.app.domain.vo.AppPackageTwoVo;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.service.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.BillType;
import com.ruoyi.common.enums.CoinType;
import com.ruoyi.common.enums.DetailEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EntityCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.app.domain.bo.AppPackageTwoOrderBo;
import com.ruoyi.app.domain.vo.AppPackageTwoOrderVo;
import com.ruoyi.app.domain.AppPackageTwoOrder;
import com.ruoyi.app.mapper.AppPackageTwoOrderMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 爬塔记录Service业务层处理
 *
 * @author heise
 * @date 2025-06-27
 */
@RequiredArgsConstructor
@Service
public class AppPackageTwoOrderServiceImpl implements IAppPackageTwoOrderService {

    private final IAppUserService appUserService;
    private final IAppAssetService appAssetService;
    private final IAppDetailService appDetailService;
    private final AppPackageTwoOrderMapper baseMapper;


    /**
     * 查询爬塔记录
     */
    @Override
    public AppPackageTwoOrderVo queryById(Long packageTorderId) {
        return baseMapper.selectVoById(packageTorderId);
    }

    /**
     * 查询爬塔记录列表
     */
    @Override
    public TableDataInfo<AppPackageTwoOrderVo> queryPageList(AppPackageTwoOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppPackageTwoOrder> lqw = buildQueryWrapper(bo);
        Page<AppPackageTwoOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询爬塔记录列表
     */
    @Override
    public List<AppPackageTwoOrderVo> queryList(AppPackageTwoOrderBo bo) {
        LambdaQueryWrapper<AppPackageTwoOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<AppPackageTwoOrderVo> queryList(LambdaQueryWrapper<AppPackageTwoOrder> wrapper) {
        return baseMapper.selectVoList(wrapper);
    }


    private LambdaQueryWrapper<AppPackageTwoOrder> buildQueryWrapper(AppPackageTwoOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppPackageTwoOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppPackageTwoOrder::getUserId, bo.getUserId());
        lqw.eq(bo.getPackageTwoId() != null, AppPackageTwoOrder::getPackageTwoId, bo.getPackageTwoId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppPackageTwoOrder::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增爬塔记录
     */
    @Override
    public Boolean insertByBo(AppPackageTwoOrderBo bo) {
        AppPackageTwoOrder add = BeanUtil.toBean(bo, AppPackageTwoOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPackageTorderId(add.getPackageTorderId());
        }
        return flag;
    }

    /**
     * 修改爬塔记录
     */
    @Override
    public Boolean updateByBo(AppPackageTwoOrderBo bo) {
        AppPackageTwoOrder update = BeanUtil.toBean(bo, AppPackageTwoOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppPackageTwoOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除爬塔记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createOrder(AppPackageTwoOrderBo bo, AppPackageTwoVo packageTwoVo) {
        Boolean result = appAssetService.subtractIntegral(bo.getUserId(), packageTwoVo.getPackagePrice());
        if (result) {
            AppPackageTwoOrderBo appPackageTwoOrderBo = new AppPackageTwoOrderBo();
            EntityCopyUtils.copyPropertiesIgnoreNull(packageTwoVo, appPackageTwoOrderBo);
            appPackageTwoOrderBo.setUserId(bo.getUserId());
            appPackageTwoOrderBo.setPackageDay(DateUtil.offsetHour(DateUtils.getNowDate(), packageTwoVo.getPackageDay().intValue()));
            appPackageTwoOrderBo.setPackageNetIncome(packageTwoVo.getPackageIncome().subtract(packageTwoVo.getPackagePrice()));
            appPackageTwoOrderBo.setStatus(Constants.SUCCESS);
            appPackageTwoOrderBo.setPackageFee(packageTwoVo.getPackageFee());
            appDetailService.insert(bo.getUserId(), packageTwoVo.getPackagePrice(),
                    BigDecimal.ZERO, BillType.TO.getCode(), CoinType.INTE.getCode(),
                    DetailEnums.CLIMBING_TOWER_TO.getCode(), "参与"+packageTwoVo.getPackageName()+"爬塔", null);
            return insertByBo(appPackageTwoOrderBo);
        }
        return result;
    }

    /**
     * 爬塔收益完成
     *
     * @param orderVo 订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void downOrder(AppPackageTwoOrderVo orderVo) {
        AppPackageTwoOrderBo orderBo = new AppPackageTwoOrderBo();
        orderBo.setStatus(Constants.FAIL);
        orderBo.setPackageTorderId(orderVo.getPackageTorderId());
        orderBo.setPackageName(orderVo.getPackageName());
        if (updateByBo(orderBo)) {
            BigDecimal packageIncome = BigDecimal.ZERO;
            if (orderVo.getPackageFee() != null) {
                BigDecimal bigDecimal = new BigDecimal("100");
                BigDecimal fee = orderVo.getPackageNetIncome().multiply(bigDecimal.subtract(orderVo.getPackageFee())).divide(bigDecimal, 2, RoundingMode.HALF_UP);
                packageIncome = orderVo.getPackagePrice().add(fee);
            } else {
                packageIncome = orderVo.getPackageIncome();
            }
            appAssetService.addIntegral(orderVo.getUserId(), packageIncome);
            appAssetService.addContribution(orderVo.getUserId(), orderVo.getPackageContribution());

            appDetailService.insert(orderVo.getUserId(), packageIncome, BigDecimal.ZERO,
                    BillType.IN.getCode(), CoinType.INTE.getCode(), DetailEnums.CLIMBING_TOWER_IN.getCode(),
                    "爬塔"+orderBo.getPackageName()+"收益", null);

            appDetailService.insert(orderVo.getUserId(), orderVo.getPackageContribution(),
                    BigDecimal.ZERO, BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(),
                    DetailEnums.CLIMBING_TOWER_IN.getCode(), "爬塔"+orderBo.getPackageName()+"收益", null);

            appUserService.paTaRewards(orderVo.getUserId(), packageIncome.subtract(orderVo.getPackagePrice()),orderBo.getPackageName());
        }
    }
}
